from aiohttp import web

from config import app_alone
from http_service import app
from nats_service import start_nats, stop_nats
from socket_io_service import sio
import torch
import os
import aiohttp_cors

cors = aiohttp_cors.setup(app, defaults={
    "*": aiohttp_cors.ResourceOptions(
        allow_credentials=True,
        expose_headers="*",
        allow_headers="*",
    )
})

for route in list(app.router.routes()):
    cors.add(route)

def create_nats():
    app.on_startup.append(start_nats)
    app.on_cleanup.append(stop_nats)

def run_http():
    web.run_app(app, host='0.0.0.0', port=8080)


def device_detector():
    from share import machine_config
    machine_config["gpu"] =  torch.cuda.is_available()
    machine_config["cpu_count"] =  os.cpu_count()
    print("gpu是否可用：",machine_config["gpu"], "cpu_数量为:",machine_config["cpu_count"] )


def choose_start_server():
    if app_alone is False:
        create_nats()
        run_http()
    else:
        create_nats()
        sio.attach(app)
        run_http()



# 主函数
if __name__ == '__main__':
    print('启动影像处理程序中...')
    device_detector()
    choose_start_server()